package com.deep.test.thread.concurrent;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *
 Thread.yield();线程让步，就是说当一个线程使用了这个方法之后，它就会把自己CPU执行的时间让掉，
 让自己或者其它的线程运行，注意是让自己或者其他线程运行，并不是单纯的让给其他线程。
 yield()的作用是让步。它能让当前线程由“运行状态”进入到“就绪状态”，从而让其它具有相同优先级的等待线程获取执行权；
 但是，并不能保证在当前线程调用yield()之后，其它具有相同优先级的线程就一定能获得执行权；
 也有可能是当前线程又进入到“运行状态”继续运行！
 * </p>
 * Created with IDEA
 * author:hudepin
 * createTime:2018/7/5 14:56
 */
public class Priority {
    public static volatile boolean notStart = true;
    public static volatile boolean notEnd = true;

    public static void main(String[] args) {
        List<Job> jobs = new ArrayList<Job>();
        for (int i=0;i<10;i++){
            int priority = i<5?Thread.MIN_PRIORITY:Thread.MAX_PRIORITY;
            Job job = new Job(priority);
            jobs.add(job);
            Thread t  = new Thread(job,"job-"+i);
            t.setPriority(priority);
            t.start();
        }
        notStart = false;
        try {
            TimeUnit.SECONDS.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        notEnd = false;
        for(Job job:jobs){
            System.out.println("Job Priority:"+job.priority+",count:"+job.jobCount);
        }

    }
    static class Job implements Runnable{
        private int priority;
        private long jobCount;
        public Job(int priority){
            this.priority = priority;
        }
        @Override
        public void run() {
            while(notStart){
                //线程让步
                Thread.yield();
            }
            while(notEnd){
                Thread.yield();
                jobCount++;
            }
        }
    }
}
